package handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import message.Message;

import java.nio.charset.StandardCharsets;

/**
 * @author wb_zhulinzhong
 * @date 2021-04-14 19:13:43
 */
public class ComMessageToByteEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        String msgText = msg.toJsonString();
        byte[] bytes = msgText.getBytes(StandardCharsets.UTF_8);

        //发送数据包长度
        out.writeInt(bytes.length);
        //发送数据包
        out.writeBytes(bytes);
    }
}
